<?php

namespace app\devices\command;

use app\devices\service\OrderService;
use think\admin\Command;
use think\admin\Exception;
use think\cache\driver\Redis;
use think\console\Input;
use think\console\Output;

/**
 * 自动清理订单相关缓存
 * Class ClearOrderCache
 * @package app\data\command
 */
class ClearOrderCache extends Command
{
    protected $redis;
    protected function configure()
    {
        $this->setName('xdevice:ClearOrderCache');
        $this->setDescription('清理订单相关缓存');
        $this->redis = new Redis();
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $this->clearOrderCache();
    }

    private function clearOrderCache(){
        $list = $this->redis->handler()->keys("orderUse*");
        foreach ($list as $key){
            $d_id = str_replace("orderUseBox","",$key);
            $box_ids = $this->app->db->name("jcg_devices_order")->where(["d_id"=>$d_id, "status"=>1])->column("box_id");
            $cache_box_ids = $this->redis->handler()->ZRANGE($key, 0, -1);

            $ids = array_diff($cache_box_ids, $box_ids);
            if($ids){
                $ids = array_merge([$key], $ids);
                call_user_func_array([$this->redis->handler(), 'ZREM'], $ids);
            }

        }
    }
}